<template>
  <div
    class="app-container flex flex-sub"
    style="background: none; height: 100%; padding: 1rem"
  >
    <el-card shadow="never" class="box-card flex-sub" style="overflow: auto">
      <div class="div-query">
        <div class="collapse">
          <div class="collapse-header" @click="panelActive = !panelActive">
            <i
              class="collapse-header-icon"
              :class="[
                panelActive ? 'el-icon-caret-bottom' : 'el-icon-caret-top',
              ]"
            />
            {{ panelActive ? '隐藏' : '展开' }}查询条件
          </div>
          <div class="collapse-content">
            <el-collapse-transition>
              <div v-show="panelActive">
                <el-form size="small" label-position="right">
                  <el-row>
                    <el-col :span="8">
                      <el-form-item label="姓名" label-width="80px">
                        <el-input
                          v-model="searchModel.name"
                          placeholder="输入姓名"
                          clearable
                          class="filter-item search-item"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="性别" label-width="80px">
                        <el-select
                          v-model="searchModel.xbdm"
                          placeholder="选择性别"
                          clearable
                          filterable
                        >
                          <el-option
                            v-for="item in xbdmList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="7" style="margin-left: 10px">
                      <el-form-item>
                        <el-button
                          type="primary"
                          icon="el-icon-search"
                          @click="toSearch"
                          style="margin-right: 10px"
                          >搜索</el-button
                        >
                        <el-button
                          type="info"
                          icon="el-icon-delete"
                          @click="toReset"
                          style="margin-right: 10px"
                          >重置</el-button
                        >
                        <el-button size="small" @click="getDataList">
                          <i class="el-icon-refresh" style="color: #606266" />
                          <span style="color: #606266">刷新</span>
                        </el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </el-collapse-transition>
          </div>
        </div>
      </div>

      <div style="margin-bottom: 1rem">
        <el-button
          size="small"
          type="primary"
          style="margin-right: 20px"
          @click="toAdd({ id: -1 }, 'add')"
        >
          <i
            class="iconfont icon-xinzenghuizong"
            style="font-size: 13px; margin-right: 5px"
          />新增
        </el-button>

        <div v-if="selectedDataList.length != 0" class="alert-div">
          <i class="el-icon-info" style="color: #1890ff; margin-right: 3px" />
          已选择
          <strong style="color: #1890ff; margin: 0px 1px; font-size: 15px">
            {{ selectedDataList.length }}
          </strong>
          项
          <el-button type="text" style="padding: 10px" @click="toEmptySelection"
            >清空</el-button
          >
        </div>

        <el-button
          icon="el-icon-s-promotion"
          @click="toDistribution('')"
          size="small"
        >
          下发人脸数据
        </el-button>

        <el-button
          icon="el-icon-s-promotion"
          @click="toDistribution('全部')"
          size="small"
        >
          全部下发人脸数据
        </el-button>

        <el-button
          type="primary"
          icon="el-icon-download"
          size="small"
          @click="downloadTemplate"
          style="margin: 0px; float: right"
          >下载模板</el-button
        >

        <el-upload
          :action="action"
          :headers="headers"
          :on-change="handleChange"
          :before-upload="beforeUpload"
          style="float: right"
        >
          <el-button
            type="info"
            icon="el-icon-upload"
            size="small"
            style="margin-right: 10px"
          >
            批量导入人脸数据
          </el-button>
        </el-upload>
      </div>

      <div>
        <el-table
          ref="elTable"
          v-loading="loading || deleteLoading"
          border
          fit
          size="medium "
          :data="dataList"
          :row-key="(row) => row.id"
          style="width: 100%"
          :element-loading-text="deleteLoading ? '删除中,请等待...' : ''"
          @sort-change="onSortChange"
          @selection-change="onSelectionChange"
        >
          <el-table-column
            align="center"
            type="selection"
            width="40"
            fixed
            :reserve-selection="true"
          />
          <el-table-column
            align="center"
            type="index"
            width="50"
            fixed
            label="#"
            :index="indexMethod"
          />
          <el-table-column align="center" label="人脸图片" prop="facePic">
            <template slot-scope="{ row }">
              <img
                :src="row.facePic"
                style="width: 40px; height: 40px; cursor: pointer"
                @click="handleImgPreview(row.facePic)"
              />
            </template>
          </el-table-column>

          <el-table-column align="center" label="姓名" prop="name" />
          <el-table-column align="center" label="身份证号" prop="sfzh" />
          <el-table-column align="center" label="性别" prop="xbdm">
            <template slot-scope="{ row }">
              {{ globalConstant.XBDM[row.xbdm].text }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="标签" prop="label" />
          <el-table-column align="center" label="备注" prop="remark" />
          <el-table-column
            align="center"
            label="操作区"
            fixed="right"
            width="180"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="{ row }">
              <el-tooltip effect="dark" content="详情" placement="top-start">
                <i
                  class="iconfont icon-chakanxiangqing2 i-detail"
                  @click="toDetail(row)"
                />
              </el-tooltip>

              <i class="iconfont icon-fengefu i-fengefu" />

              <el-tooltip effect="dark" content="编辑" placement="top-start">
                <i
                  class="iconfont icon-bianji2 i-edit"
                  @click="toAdd(row, 'edit')"
                />
              </el-tooltip>

              <i class="iconfont icon-fengefu i-fengefu" />

              <el-tooltip effect="dark" content="删除" placement="top-start">
                <el-popconfirm
                  :title="'确定删除【' + row.name + '】该人员吗？'"
                  placement="top"
                  @confirm="toSingleDelete(row, '确定')"
                  @cancel="toSingleDelete(row, '取消')"
                >
                  <i class="iconfont icon-shanchu i-delete" slot="reference" />
                </el-popconfirm>
              </el-tooltip>

              <i class="iconfont icon-fengefu i-fengefu" />

              <el-tooltip
                effect="dark"
                content="查看下发记录"
                placement="top-start"
              >
                <i
                  class="el-icon-s-promotion i-edit"
                  @click="toDistributionRecords(row)"
                />
              </el-tooltip>

              <i class="iconfont icon-fengefu i-fengefu" />

              <el-tooltip
                effect="dark"
                content="查看挂载设备"
                placement="top-start"
              >
                <i
                  class="el-icon-video-camera i-edit"
                  @click="toLookBelongDevices(row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="pagination.pageNum"
          :limit.sync="pagination.pageSize"
          :page-sizes="pageSizeOptions"
          @pagination="getDataList"
        />
      </div>
    </el-card>

    <el-dialog
      :visible.sync="imgDialogVisible"
      :title="'人脸图片'"
      top="80px"
      width="500px"
    >
      <img :src="dialogImageUrl" alt="" style="padding: 20px; width: 100%" />
    </el-dialog>

    <personnel-records-add
      ref="addDialog"
      :dialog-visible="addDialogObj.isVisible"
      :title="addDialogObj.title"
      :params="params"
      @close="dialogClose('addDialogObj')"
      @submit="afterSubmit"
      v-if="addDialogObj.isVisible"
    />

    <personnel-records-detail
      ref="detailDialog"
      :dialog-visible="detailDialogObj.isVisible"
      :title="detailDialogObj.title"
      :params="params"
      @close="dialogClose('detailDialogObj')"
      v-if="detailDialogObj.isVisible"
    />

    <personnel-distribution-records
      ref="distributionRecordsDialog"
      :dialog-visible="distributionRecordsDialogObj.isVisible"
      :title="distributionRecordsDialogObj.title"
      :item="params"
      @close="dialogClose('distributionRecordsDialogObj')"
      v-if="distributionRecordsDialogObj.isVisible"
    />

    <personnel-distribution
      ref="distributionDialog"
      :dialog-visible="distributionDialogObj.isVisible"
      :title="distributionDialogObj.title"
      :selectedDataList="selectedDataList"
      :operationType="distributionDialogObj.operationType"
      @close="dialogClose('distributionDialogObj')"
      @submit="afterDistribution"
      v-if="distributionDialogObj.isVisible"
    />

    <personnel-belong-devices
      ref="BelongDevicesDialog"
      :dialog-visible="belongDevicesDialogObj.isVisible"
      :title="belongDevicesDialogObj.title"
      :item="params"
      @close="dialogClose('belongDevicesDialogObj')"
      v-if="belongDevicesDialogObj.isVisible"
    />
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import dataTableMixins from '@/mixins/data-table-mixins'
import EpidemicPreventionManageApi from '@/api/epidemic-prevention-manage'
import globalConstant from '@/utils/constants'
import PersonnelRecordsAdd from './component/Add'
import PersonnelRecordsDetail from './component/Detail'
import PersonnelDistributionRecords from './component/DistributionRecords'
import PersonnelDistribution from './component/Distribution'
import PersonnelBelongDevices from './component/BelongDevices'
import { getToken } from '@/utils/auth'
export default {
  components: {
    Pagination,
    PersonnelRecordsAdd,
    PersonnelRecordsDetail,
    PersonnelDistributionRecords,
    PersonnelDistribution,
    PersonnelBelongDevices,
  },
  mixins: [dataTableMixins],
  data() {
    return {
      deleteLoading: false,
      xbdmList: [
        {
          label: '未知的性别',
          value: '0',
        },
        {
          label: '男性',
          value: '1',
        },
        {
          label: '女性',
          value: '2',
        },
        {
          label: '未说明的性别',
          value: '9',
        },
      ],
      imgDialogVisible: false,
      dialogImageUrl: '',

      distributionRecordsDialogObj: {
        title: '',
        isVisible: false,
      },
      distributionDialogObj: {
        title: '',
        isVisible: false,
        operationType: '',
      },

      action: process.env.VUE_APP_BASE_API + 'epidemics/person/import',
      headers: {
        Authorization: `bearer ${getToken()}`,
      },
      loadingTemp: null,

      belongDevicesDialogObj: {
        title: '',
        isVisible: false,
      },
    }
  },
  computed: {
    globalConstant() {
      return { ...globalConstant }
    },
  },
  mounted() {
    this.getDataList()
  },
  methods: {
    getDataList() {
      this.loading = true
      const searchModel = this.formatSearchData(this.searchModel)
      EpidemicPreventionManageApi.getPersonList({
        ...this.pagination,
        ...searchModel,
        ...this.sort,
      })
        .then((res) => {
          if (res.data.code == 200) {
            this.dataList = res.data.data.rows

            this.dataList.forEach((ele, i) => {
              this.selectedDataList.forEach((multEle, j) => {
                if (this.dataList[i].id === this.selectedDataList[j].id) {
                  this.$refs.elTable.toggleRowSelection(this.dataList[i], true)
                }
              })
            })

            this.total = res.data.data.total
            this.loading = false
          }
        })
        .catch(() => {
          this.loading = false
          this.dataList = []
          this.total = 0
        })
    },
    toSearch() {
      this.pagination.pageNum = 1
      this.getDataList()
    },
    toReset() {
      this.searchModel = {}
      this.sort = {}
      this.$refs.elTable.clearSort()
      this.$refs.elTable.clearFilter()
      this.toSearch()
    },
    onSortChange(val) {
      this.sort.field = val.prop
      this.sort.order = val.order
      this.toSearch()
    },
    onSelectionChange(selection) {
      this.selectedDataList = selection
    },
    toEmptySelection() {
      this.$refs.elTable.clearSelection()
    },
    indexMethod(index) {
      return this.formatIndex(index, this.pagination)
    },
    toAdd(data, type) {
      this.params = {
        item: data,
        type: type,
      }
      this.addDialogObj.title =
        type === 'edit'
          ? '防疫管理 ＞人员记录 ＞编辑'
          : '防疫管理 ＞人员记录 ＞添加'
      this.addDialogObj.isVisible = true
    },
    afterSubmit(operationType) {
      if (operationType === 'add') {
        this.toReset()
      } else {
        this.getDataList()
      }
    },
    toSingleDelete(data, type) {
      if (type === '确定') {
        this.deleteConfirm(data.id, '')
      }
    },
    deleteConfirm(id) {
      this.deleteLoading = true
      const data = {
        id: id,
      }
      EpidemicPreventionManageApi.deletePerson(data)
        .then((res) => {
          if (res.data.code == 200) {
            this.$message({
              message: '删除成功！',
              type: 'success',
            })
            this.deleteLoading = false
            this.toEmptySelection()
            this.toReset()
          } else {
            this.$message({
              message: '删除失败！',
              type: 'error',
            })
            this.deleteLoading = false
          }
        })
        .catch((err) => {
          this.deleteLoading = false
        })
    },
    toDetail(data) {
      this.params = {
        item: data,
      }
      this.detailDialogObj.title = '防疫管理 ＞人员记录  ＞详情'
      this.detailDialogObj.isVisible = true
    },
    toDistributionRecords(data) {
      this.params = {
        item: data,
      }
      this.distributionRecordsDialogObj.title =
        '防疫管理 ＞人员记录  ＞下发记录'
      this.distributionRecordsDialogObj.isVisible = true
    },
    toDistribution(type) {
      if (type == '') {
        if (this.selectedDataList.length == 0) {
          this.$message.warning('请选择需要下发的人脸数据')
          return false
        }
      }

      this.distributionDialogObj.title =  `防疫管理 ＞人员记录  ＞${type}下发人脸数据`
      this.distributionDialogObj.operationType = type
      this.distributionDialogObj.isVisible = true
    },
    afterDistribution() {
      this.toEmptySelection()
    },

    handleImgPreview(url) {
      this.dialogImageUrl = url
      this.imgDialogVisible = true
    },

    handleChange(file, fileList) {
      console.log('file', file)
      this.loadingTemp = this.$loading({
        lock: true,
        text: '正在导入数据，请稍候',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })

      switch (file.status) {
        case 'ready':
          break
        case 'success':
          this.loadingTemp.close()
          if (file.response.code == 200) {
            this.$message.success(`${file.name} 文件导入成功.`)
            this.toReset()
          } else {
            this.$message.error('导入文件失败!')
          }

          // if (file.response == '导入成功') {
          //   this.$message.success(`${file.name} 文件导入成功.`)
          // } else {
          //   this.$message.error('导入文件失败，失败原因：' + file.response.msg)
          // }

          break
        case 'fail':
          this.loadingTemp.close()
          this.$message.error('导入文件失败，请重新导入！')
      }
    },

    beforeUpload(file) {
      console.log('file=', file)
      const isCompressFile =
        file.type === 'application/x-zip-compressed' ||
        file.type === 'application/x-rar-compressed'

      if (!isCompressFile) {
        this.$message.error('只能上传后缀为.zip和.rar的文件!')
        this.loadingTemp.close()
      }

      return isCompressFile
    },

    // 下载模板
    downloadTemplate() {
      window.location.href = 'http://47.106.193.127:9527/template/template.zip'
    },

    toLookBelongDevices(data) {
      this.params = {
        item: data,
      }
      this.belongDevicesDialogObj.title = '防疫管理 ＞人员记录  ＞挂载设备'
      this.belongDevicesDialogObj.isVisible = true
    },
  },
}
</script>


<style lang="scss"  scoped>
@import '../../../../styles/part-custom';
</style>